package com.example.birthday_getway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository;

@Configuration
@EnableWebFluxSecurity // 替换 @EnableWebSecurity
public class SecurityConfig {

  @Bean
  public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { // 参数和返回类型变更
    http
        // 禁用CSRF
        .csrf(csrf -> csrf.disable())

        // 配置无状态会话
        .securityContextRepository(
            NoOpServerSecurityContextRepository.getInstance()) // 替代 sessionManagement

        // 配置请求授权
        .authorizeExchange(
            auth -> // 替换 authorizeHttpRequests
            auth
                    // 允许所有OPTIONS请求
                    .pathMatchers(HttpMethod.OPTIONS, "/**")
                    .permitAll()

                    // 公开访问的路径
                    .pathMatchers("/api/auth/login")
                    .permitAll()
                    .pathMatchers("/api/auth/register")
                    .permitAll()
//                    .pathMatchers("/api/auth/rate")
//                    .permitAll()
                    .pathMatchers("/api/auth/**")
                    .permitAll()
                    // 其他请求需要认证
                    .anyExchange()
                    .authenticated())
        // 添加JWT过滤器
        .addFilterAt(new JwtWebFilter(), SecurityWebFiltersOrder.AUTHENTICATION); // 添加位置变更
    return http.build();
  }
}
